<template>
  <div class="add_or_edit_form">
    <el-dialog :visible.sync="visible"
               ref="dialog"
               :lock-scroll="true"
               title="Add Form"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               @open="open"
               @close="clearFormData">
        <div v-loading="loading">
        <el-form :model="dataForm"
                 :inline="true"
                 :rules="dataRule"
                 ref="form"
                 label-width="100px"
                 label-position="top"
                 class="userForm-dataForm">
          <el-form-item label="Name:"
                        prop="formTitle">
            <el-input style="width:252px"
                      v-model="dataForm.formTitle" maxlength="120" show-word-limit></el-input>
          </el-form-item>
        <el-form-item prop="roleIds"
                            label="Role:">
       <el-select v-model="dataForm.roleIds"
                           filterable
                           clearable
                           multiple
                           collapse-tags
                           default-first-option
                           :placeholder="$t('custom.dataset.role')"
                           style="width: 90%;">
                  <el-option v-for="its in roleList"
                             :key="its.id"
                             :label="its.name"
                             :value="its.roleId"></el-option>
                </el-select>
              </el-form-item>

        <!-- <el-form-item prop="integration"
                            :label="$t('custom.dataset.integration')">
                <el-select v-model="dataForm.integration"
                           multiple
                           collapse-tags
                           v-loading="integrationLoding"
                           :placeholder="$t('custom.dataset.integration')"
                           style="width: 90%;">
                  <el-option v-for="its in integrationList"
                             :key="its.subjectCode"
                             :label="its.name"
                             :value="its.subjectCode"></el-option>
                </el-select>
              </el-form-item> -->

          <el-form-item label="Description:"
                        style="margin-left:30px"
                        prop="description">
            <el-input type="textarea"
                      :rows="1"
                      style="width:252px"
                      v-model="dataForm.description"></el-input>
          </el-form-item>
          <el-form-item label=""
                        style="float:right;margin-right:0">
            <div style="float:right;padding:25px 0 0">
              <el-button size="small"
                         style="width:80px"
                         :loading="btnLoading"
                         @click="clearFormData">Cancel</el-button>
              <el-button type="primary"
                         style="width:80px"
                         size="small"
                         :loading="btnLoading"
                         @click="save">Save</el-button>
            </div>
          </el-form-item>
        </el-form>
        <FormMaking :dialogData="dataForm"
                    ref="makingForm"></FormMaking>
                  </div>
                </el-dialog>
        <fm-generate-form v-if="jsonShow" :data="jsonData1" ref="generateForm"></fm-generate-form>
  </div>
</template>

<script>
import FormMaking from './form-making.vue'
import { isIncludeSymbol } from '@/utils/validate'
import { unionIntegrationList } from '@/components/storybook/utilties/tools'
import { jsonData } from '@/components/script-render/components/type-card/card-link-button'
export default {
  components: {
    FormMaking
  },
  data () {
    return {
      jsonShow:false,
      jsonData1:{},
      visible: false,
      loading: false,
      roleList: [],
      dataForm: {
        formTitle: '',
        roleIds: [],
        description: '',
        createTime: '',
        formSchema: '',
        businessType: 'Custom',
        status: 'Published',
        tenantCode: this.$store.state.user.tenantCode,
        integration: []
      },
      integrationList: [],
      integrationLoding: false,
      btnLoading: false
    }
  },
  watch: {
    visible (val) {
      if (!val) {
        this.clearFormData()
      }
    }
  },
  computed: {
    dataRule () {
      var validateSymbol = (rule, value, callback) => {
        if (!isIncludeSymbol(value)) {
          return callback(new Error(this.$t('validate.isIncludeSymbol')))
        }
        callback()
      }
      return {
        formTitle: [
          { required: true, message: 'Please enter the name', trigger: 'blur', pattern: '[^ \x22]+' },
          { validator: validateSymbol, trigger: 'blur' },
          { validator: this.nameValidate, trigger: 'blur' }
        ],
        formSchema: [
          { required: true, message: 'Please making the form', trigger: 'blur' }
        ],
        roleIds: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        description: [
          { required: true, message: 'Please enter the description', trigger: 'blur', pattern: '[^ \x22]+' }
        ]
      }
    }
  },
  methods: {
    init () {
      this.loading = true
      this.visible = true
      this.getRoleList()
      // this.getIntegrationList()
      this.$nextTick(() => {
        if (this.dataForm.formCode) {
          this.getInfo()
        } else {
          this.loading = false
        }
      })
    },
    setRuleList () {
      if (this.roleList.length > 0) {
        this.dataForm.roleIds = this.dataForm.roleIds.filter(e => this.roleList.findIndex(o => o.roleId === e) > -1)
      } else {
        setTimeout(() => {
          this.setRuleList()
        }, 800)
      }
    },
    getInfo () {
      const params = {
        formCode: this.dataForm.formCode
      }
      this.$interface.reports.getFormDataInfo(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataForm = res.data
        this.setRuleList()
        if (this.$refs['makingForm']) {
          this.$refs['makingForm'].queryMakingForm(this.dataForm.formSchema)
        }
        this.loading = false
      })
    },
    getRoleList () {
      const params = {
        tenantCode: this.$store.state.user.tenantCode
      }
      this.$interface.system.getClientRoleListApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.roleList = res.data
        }).catch(() => { })
    },
    getIntegrationList () {
      this.integrationLoding = true
      const params = {
        tenantCode: this.$store.state.user.tenantCode,
        loadType: 3
      }
      return this.$interface.taskManager.getConnectorInfoNew(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          let mapObj = res.data
          let tempList = []
          for (let key in mapObj) {
            tempList.push({
              name: mapObj[key].name,
              subjectCode: mapObj[key].sync.subjectCode,
              status: mapObj[key].sync.status
            })
          }
          this.integrationList = unionIntegrationList(tempList, 'subjectCode')
          this.integrationLoding = false
        })
        .catch(() => { })
    },
    clearFormData () {
      if(this.$refs['form']) this.$refs['form'].resetFields()
      this.dataForm = {
        formTitle: '',
        roleIds: [],
        description: '',
        createTime: '',
        formSchema: ''
      }
      if (this.$refs['makingForm']) {
        this.$refs['makingForm'].clearMakingForm()
      }
      this.visible = false
    },
    nameValidate (rule, value, callback) {
      var params = {}
      params.formTitle = this.dataForm.formTitle
      if (this.dataForm.formCode) {
        params.formCode = this.dataForm.formCode
      }
      this.$interface.reports.getCheckFromNameApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return callback(new Error('The name is already exists'))
          }
          callback()
        })
    },
    save () {
      this.btnLoading = true
      this.$refs.form.validate(pass => {
        if (pass) {
          const params = {
            ...this.dataForm
          }
          params.formSchema = this.$refs.makingForm.getJson()
          this.jsonData1 = params.formSchema
          this.jsonShow = true
          this.$nextTick(()=>{
            setTimeout(() => {
              this.$refs.generateForm.getData(false).then(res=>{
                params.dataContent = res
                this.jsonShow = false
                if (params.formSchema.list.length < 1) {
                  this.btnLoading = false
                  return this.$message.error('Please making the form')
                }
                this.loading = true
                this.$interface.reports.addOrUpdateFormApi(params).then(({ data: res }) => {
                  this.btnLoading = false
                  if (res.code !== 0) {
                    this.loading = false
                    return this.$message.error(res.msg)
                  } else {
                    this.addReportRouter(res.data)
                    this.$emit('refreshDataList')
                    if (!this.dataForm.formCode) {
                      this.visible = false
                    }
                    this.$message.success(res.msg)
                    this.loading = false
                  }
                })
              })
              .catch(e=>{
                this.jsonShow = false
                this.btnLoading = false
              })
            }, 0);
          })
        }else{
          this.btnLoading = false
        }
      })
    },
    open () {
      if (this.$refs['dataForm']) {
        this.$refs['dataForm'].clearValidate()
      }
    },
    addReportRouter (route) {
      let childrenrouterMenu =
      {
        children: [],
        createDate: null,
        hasChildren: null,
        hideFromMenu: true,
        icon: 'icon-detail',
        id: route.formCode,
        name: 'form-' + route.formTitle,
        param: JSON.stringify({ 'formCode': route.formCode }),
        parentName: null,
        permissions: '0',
        pid: '',
        sort: 0,
        type: 0,
        url: 'mspbots/FormList/FormData/index'
      }
      let menuList = window.SITE_CONFIG['menuList']
      let formList = menuList.find(it => {
        return it.name === 'Form List'
      })
      if (!formList) {
        let arr = []
        menuList.forEach(item => {
          arr = arr.concat(item.children)
        })
        formList = arr.find(it => {
          return it.name === 'Form List'
        })
      }
      formList.children.push(childrenrouterMenu)
    }
  }
}
</script>

<style lang="scss">
.add_or_edit_form {
  .el-dialog {
    // min-width: 768px;
    width: 90vw;
    position: relative;
    margin: auto;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
  }
  .el-dialog__body {
    padding: 20px !important;
  }
  .userForm-dataForm {
    margin-bottom: 5px;
  }
  .el-dialog {
    display: flex;
    flex-direction: column;
    margin: 0 !important;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    /*height:600px;*/
    max-height: calc(100% - 30px);
    max-width: calc(100% - 30px);
  }
  .el-dialog .el-dialog__body {
    flex: 1;
    overflow: auto;
  }
}
</style>
